<?php
namespace Common\Lib\Baidu;
/**
 * 百度语音识别
 * author universe.h 2017.10.27
 */
class Btt {
 /**
 *获取百度token*
 **/
     public function get_token(){
  			$file = IA_ROOT . "/data/upload/baidu_token";
			$data = file_get_contents($file);
			$token = json_decode($data, true);
      	if (empty($data) || $token["time"] + $token["expires_in"] <= time()) {
           	$baidu_token_url = "https://aip.baidubce.com/oauth/2.0/token";
            $baidu_token_data['grant_type']  = 'client_credentials';
            $baidu_token_data['client_id']   = 'Fj0FgKa3RNNvEStp3P0fxGGS';
            $baidu_token_data['client_secret'] = 'a3289e989e3dc6bb55a891ed07fb9d55';
            $o = "";
            foreach($baidu_token_data as $k => $v ) {
                $o.= "$k=" . urlencode( $v ). "&" ;
           	 }
            $post_data = substr($o,0,-1);
            $res = request_post($baidu_token_url, $baidu_token_data);
         	$res = json_decode($res, true);
       		 if ($res["access_token"]) {
           		 $token = array("access_token" => $res["access_token"], "time" => time(), "expires_in" => $res["expires_in"]);
            	 file_put_contents($file, json_encode($token));
         	 } else {
            	 file_put_contents($file, $res);
          		 $this->ajaxReturn(['code'=>40000, 'msg'=>'语音识别接口有误']);
          		}
        }
       return $token;  
  }

  
  /***百度语音转文字**/
  public function WavTotext($baidu_token,$zm_wav_file){
    $wavtotext_url ="http://vop.baidu.com/server_api";
    $wavcontent = base64_encode(file_get_contents($zm_wav_file));
  	$wavtotext_data=array(
      	'cuid'=>'00-16-3e-0d-bb-40',
      	'format'=>'wav',
      	'rate'=>'16000',
      	'channel'=>'1',
      	'token'=>$baidu_token['access_token'],
      	'speech'=>$wavcontent,
      	'len'=>filesize($zm_wav_file)  ///www/wwwroot/mall.0itc.com/16k.wav
     	);
    $headers = array("Content-type: application/json;charset='utf-8'", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
	$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $wavtotext_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wavtotext_data));
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 6000);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 6000);
        $content = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($code === 0){
            throw new Exception(curl_error($ch));
        }
        curl_close($ch);
    return $content;   
  }

}

